#include <iostream>
using std::cout;
using std::endl;
//第一个方式栈对象来托管
class Singleton{
public:
    static Singleton * getInstance(){
        if(_pInstance == nullptr){
            //这个地方new，那么需要成对出现delete
            _pInstance = new Singleton();
        }
        return _pInstance;
    }
    //单例自动释放时，就可以把这个代码注释了
#if 0
    static void destroy(){
        if(_pInstance){
            delete _pInstance;
            _pInstance = nullptr;
        }
    }
#endif
    void print(){
        cout << "Singleton::print()" << endl;
    }
    friend class AutoRelease;
private:
    Singleton(){}
    ~Singleton(){}
    Singleton(const Singleton & rhs) = delete;
    static Singleton * _pInstance;

};
Singleton * Singleton::_pInstance = nullptr;

class AutoRelease{
public:
    AutoRelease(Singleton * s)
    :_ps(s)
    {

    }

    ~AutoRelease(){
        if(_ps){
            delete _ps;
            _ps = nullptr;
        }
    }

    Singleton * operator->(){
        return _ps;
    }
    Singleton & operator*(){
        return *_ps;
    }

private:
    Singleton * _ps;
};


void test(){
    AutoRelease ar(Singleton::getInstance());
    //为了能够更好的使用singleton里面的数据成员、成员函数
    //可以对运算符进行重载
    ar->print();
    ar.operator->()->print();
}

void test2(){
    AutoRelease ar(Singleton::getInstance());
    AutoRelease ar2(Singleton::getInstance());
}

int main()
{
    test2();
    return 0;
}

